#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "sqleditor.h"
#include "dbinfoeditor.h"
#include "commdefine.h"
#include <QToolButton>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    ui->splitter->setStretchFactor(1, 90);

    QToolButton *addTab = new QToolButton(ui->tabWidget);
    connect(addTab, &QToolButton::clicked, this, &MainWindow::addTab_clicked);
    connect(ui->tabWidget->tabBar(), &QTabBar::tabCloseRequested, this, &MainWindow::tabCloseRequested);
    addTab->setText("+");
    ui->tabWidget->setCornerWidget(addTab);
    ui->tabWidget->tabBar()->setTabsClosable(true);

//    showMaximized();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::connectDatabase(QTreeWidgetItem *item)
{
    if(item->childCount() > 0)
        return;
    int row = ui->treeWidget->currentIndex().row();
    if(row >= m_dbInfoList.size())
        return;

    DatabaseInfo dbInfo = m_dbInfoList.at(row);
    MysqlDB db(dbInfo.connName);
    db.setDatabaseInfo(dbInfo);
    QStringList names = db.databaseNames();
    for(auto d : names)
    {
        QTreeWidgetItem *child = new QTreeWidgetItem(item);
        child->setText(0, d);
    }

    QFont font = item->font(0);
    font.setBold(true);
    item->setFont(0, font);
}

void MainWindow::openDatabase(QTreeWidgetItem *item, const QString &dbName)
{
    if(item->childCount() > 0)
        return;
    int row = -1;
    int count = ui->treeWidget->topLevelItemCount();
    for(int i = 0; i < count; i++)
    {
        if(item->parent() == ui->treeWidget->topLevelItem(i))
        {
            row = i;
            break;
        }
    }
    if(row < 0 || row >= m_dbInfoList.size())
        return;


    m_currentDB = dbName;
    m_dbInfoList[row].dbName = dbName;
    DatabaseInfo dbInfo = m_dbInfoList.at(row);
    MysqlDB db(dbInfo.connName);
    db.setDatabaseInfo(dbInfo);
    QStringList names = db.tables();
    for(auto d : names)
    {
        QTreeWidgetItem *child = new QTreeWidgetItem(item);
        child->setText(0, d);
    }
}

void MainWindow::openTable(QTreeWidgetItem *item)
{
    int row = -1;
    int count = ui->treeWidget->topLevelItemCount();
    for(int i = 0; i < count; i++)
    {
        if(item->parent()->parent() == ui->treeWidget->topLevelItem(i))
        {
            row = i;
            break;
        }
    }
    if(row < 0 || row >= m_dbInfoList.size())
        return;

    SqlEditor *w = new SqlEditor(ui->tabWidget->tabBar());
    QString title = m_currentDB + "@" + item->text(0);
    ui->tabWidget->addTab(w, title);
    QString sql = QString("select * from %1 limit 1000;").arg(item->text(0));
    w->setDatabaseInfo(m_dbInfoList.at(row));
    w->setSqlText(sql);
    w->runSql();
}



void MainWindow::addTab_clicked()
{
    SqlEditor *w = new SqlEditor(ui->tabWidget->tabBar());
    ui->tabWidget->addTab(w, "new");
}

void MainWindow::tabCloseRequested(int index)
{
    // 关闭子页后立即释放内存。如果不释放内存，会在软件关闭时释放内存
    SqlEditor *w = qobject_cast<SqlEditor *>(ui->tabWidget->widget(index));
    w->deleteLater();
    w = Q_NULLPTR;
    ui->tabWidget->removeTab(index);
}

void MainWindow::on_actionQuery_triggered()
{
    SqlEditor *w = new SqlEditor(ui->tabWidget->tabBar());
    ui->tabWidget->addTab(w, "new query");
}

void MainWindow::on_actionNewConn_triggered()
{
    DbInfoEditor *editor = new DbInfoEditor(this);
    if(editor->Accepted == editor->exec())
    {
        DatabaseInfo dbInfo = editor->databaseInfo();
        m_dbInfoList.append(dbInfo);

        QTreeWidgetItem *item = new QTreeWidgetItem(ui->treeWidget);
        item->setText(0, dbInfo.connName);
    }
    else
    {
        qInfo() << "reject";
    }
    editor->deleteLater();
    editor = Q_NULLPTR;
}

void MainWindow::on_treeWidget_itemDoubleClicked(QTreeWidgetItem *item, int column)
{
    TreeFunc depth = TreeFunc(treeDepth(item));
    switch (depth) {
    case TF_CONN:
        connectDatabase(item);
        break;
    case TF_DATABASE:
        openDatabase(item, item->text(column));
        break;
    case TF_TABLE:
        openTable(item);
        break;
    default:
        break;
    }
}

void MainWindow::on_actionRun_triggered()
{
    SqlEditor *editor = qobject_cast<SqlEditor*>(ui->tabWidget->currentWidget());
    QString text = editor->sqlText();
    if(text.isEmpty())
        return;
    editor->runSql();
}
